package com.tsyz.servlet.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CookieUtil {

    public static final String TOKEN_COOKIE_NAME = "AUTH_TOKEN";

    // 从配置文件中读取是否启用HTTPS
    @Value("${tsyz.server.ssl.https.enabled:false}")
    private boolean isSslEnabled;

    /**
     * 设置认证Token Cookie
     */
    public void setTokenCookie(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie(TOKEN_COOKIE_NAME, token);
        // 防止XSS攻击
        cookie.setHttpOnly(true);
        // 根据是否启用SSL来设置Secure标志
        cookie.setSecure(isSslEnabled);
        cookie.setPath("/"); // 对所有路径有效
        cookie.setMaxAge(7 * 24 * 60 * 60); // 7天过期

        // 构建Cookie头部字符串
        StringBuilder cookieHeader = new StringBuilder();
        cookieHeader.append(String.format("%s=%s", cookie.getName(), cookie.getValue()));

        // 添加Domain属性（如果需要）
        // 注意：在没有明确设置Domain的情况下，Cookie只对当前域名有效
        // 这有助于防止跨站请求伪造攻击
        cookieHeader.append(String.format("; Path=%s", cookie.getPath()));
        cookieHeader.append(String.format("; Max-Age=%d", cookie.getMaxAge()));

        // 只在启用SSL时设置Secure标志
        if (isSslEnabled) {
            cookieHeader.append("; Secure");
        }

        cookieHeader.append("; HttpOnly");
        cookieHeader.append("; SameSite=Strict");

        response.addHeader("Set-Cookie", cookieHeader.toString());
    }

    /**
     * 从请求中获取Token Cookie
     */
    public String getTokenFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (TOKEN_COOKIE_NAME.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 删除Token Cookie
     */
    public void removeTokenCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie(TOKEN_COOKIE_NAME, null);
        cookie.setHttpOnly(true);
        // 根据是否启用SSL来设置Secure标志
        cookie.setSecure(isSslEnabled);
        cookie.setPath("/");
        cookie.setMaxAge(0); // 立即过期

        // 构建Cookie头部字符串
        StringBuilder cookieHeader = new StringBuilder();
        cookieHeader.append(String.format("%s=%s", cookie.getName(), cookie.getValue()));

        // 添加Domain属性（如果需要）
        cookieHeader.append(String.format("; Path=%s", cookie.getPath()));
        cookieHeader.append(String.format("; Max-Age=%d", cookie.getMaxAge()));

        // 只在启用SSL时设置Secure标志
        if (isSslEnabled) {
            cookieHeader.append("; Secure");
        }

        cookieHeader.append("; HttpOnly");
        cookieHeader.append("; SameSite=Strict");

        response.addHeader("Set-Cookie", cookieHeader.toString());
    }

    /**
     * 设置Cookie的安全属性
     * 这个方法可以根据需要动态设置Cookie的安全属性
     */
/*    public void setTokenCookieWithSecurity(HttpServletResponse response, String token, boolean isSecure) {
        Cookie cookie = new Cookie(TOKEN_COOKIE_NAME, token);
        cookie.setHttpOnly(true);
        cookie.setSecure(isSecure);
        cookie.setPath("/");
        cookie.setMaxAge(7 * 24 * 60 * 60); // 7天过期

        StringBuilder cookieHeader = new StringBuilder();
        cookieHeader.append(String.format("%s=%s", cookie.getName(), cookie.getValue()));
        cookieHeader.append(String.format("; Path=%s", cookie.getPath()));
        cookieHeader.append(String.format("; Max-Age=%d", cookie.getMaxAge()));

        if (isSecure) {
            cookieHeader.append("; Secure");
        }

        cookieHeader.append("; HttpOnly");
        cookieHeader.append("; SameSite=Strict");

        response.addHeader("Set-Cookie", cookieHeader.toString());
    }*/
}
